//index.js
//获取应用实例
const app = getApp();
const util = require('../../utils/util');

let showTabs = true;

Page({
  data: {
    userInfo: null,
    inputValue: '',
    scrollTop: 0,   // 滚动条的高度
    chatData: []
  },
  // 初次加载
  onLoad() {
    if (app.globalData.userInfo) {
      this._loadFunction();
    }
    else {
      app.globalData.userInfoReadyCallback = () => {
        this._loadFunction();
      }
    }
  },
  // 页面下拉刷新
  onPullDownRefresh(e) {
    this.loadMoreHanlder(() => wx.stopPullDownRefresh());
  },


  _loadFunction() {
    this.userInfo = app.globalData.userInfo;
    this.setData({
      userInfo: app.globalData.userInfo
    }, () => this.loadChatData());
  },

  // 加载数据
  loadChatData() {
    const chatData = [
      {
        from: { nickName: '刚刚好。', gender: 1 },
        message: { type: 'text', data: '你好' }
      },
      {
        from: { nickName: '初学者', gender: 2 },
        message: { type: 'text', data: '你好啊' }
      },
      {
        from: { nickName: '刚刚好。', gender: 1 },
        message: { type: 'text', data: '哈哈' }
      }
    ];
    this.setData({ chatData }, () => this.scrollToBottom(chatData.length));
  },

  // 滚动页面
  scrollToBottom(itemLength) {
    wx.createSelectorQuery().select('.chat-item').boundingClientRect((rect) => {
      // 使页面滚动到底部
      this.setData({ scrollTop: rect.height * itemLength });
    }).exec();
  },

  // 输入变化
  inputValueChanged(e) {
    const value = e.detail.value;
    this.data.inputValue = value;
    return value;
  },

  // 点击输入框
  inputFocusHandler() {
    wx.hideTabBar({ aniamtion: true });
  },
  // 输入框失去焦点
  inputBlurHandler() {
    wx.showTabBar({ aniamtion: true });
  },

  doubleTapHandler(e) {
    util.doubleTap(this, e, () => {
      if (showTabs) {
        wx.hideTabBar({ aniamtion: true });
      }
      else {
        wx.showTabBar({ aniamtion: true });
      }
      showTabs = !showTabs;
    });
  },

  // 加载更多聊天数据
  loadMoreHanlder(loadEndCb) {
    const chatData = this.data.chatData.concat([
      {
        from: { nickName: '刚刚好。', gender: 1 },
        message: { type: 'text', data: '你好' }
      },
      {
        from: { nickName: '初学者', gender: 2 },
        message: { type: 'text', data: '你好啊' }
      },
      {
        from: { nickName: '刚刚好。', gender: 1 },
        message: { type: 'text', data: '哈哈' }
      },
      {
        from: { nickName: '刚刚好。', gender: 1 },
        message: { type: 'text', data: '你好' }
      }
    ]);
    this.setData({ chatData });
    loadEndCb();
  }
})
